#ifndef __THREAD_POOL_H__
#define __THREAD_POOL_H__

#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>

class ThreadPool {
private:
    static ThreadPool* pinstance_;
    static std::mutex singleton_mutex_;

    // 线程池中的工作线程
    std::vector<std::thread> workers_;
    // 任务队列
    std::queue<std::function<void()>> tasks_;

    // 互斥量，保护任务队列
    std::mutex queue_mutex_;
    // 条件变量，使用等待-通知机制实现任务添加和线程唤醒
    std::condition_variable condition_;

    // 是否停止线程池中的所有线程标志，使用 std::atomic_bool 实现线程安全
    bool stop_;

protected:
    explicit ThreadPool(int thread_count); 
    ~ThreadPool();
    int threadcount_;

public:
    ThreadPool(ThreadPool &other) = delete;
    void operator=(const ThreadPool &) = delete;
    static ThreadPool* GetInstance(int thread_count);

    int threadcount() const {
        return threadcount_;
    }

    // 添加任务到线程池中并执行
    template <typename F, typename... Args>
    void enqueue(F&& f, Args&&... args) {
        {
            std::unique_lock<std::mutex> lock(queue_mutex_);
            if (stop_) {
                throw std::runtime_error("enqueue on stopped ThreadPool");
            }
            tasks_.emplace(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
        }
        condition_.notify_one();
    }
};


#endif